<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品编辑</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
        }
        
        .admin-layout {
            background-color: #f7f7f7;
        }
        
        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 24px;
            margin: 20px;
        }
        
        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }
        
        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }
        
        /* iOS风格表单 */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }
        
        .form-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }
        
        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }
        
        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }
        
        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }
        
        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }
        
        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }
        
        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }
        
        .btn-action {
            min-width: 120px;
        }
        
        /* 左侧菜单样式 */
        .submenu {
            display: none;
        }
        
        .menu-item.active > .submenu {
            display: block;
        }
        
        .menu-arrow {
            transition: transform 0.2s;
        }
        
        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }
        
        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-wrapper {
                padding: 16px;
                margin: 10px;
            }
            
            .form-container {
                padding: 0;
            }
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- 顶部导航栏 -->
        <header class="admin-header">
            <div class="header-left">
                <div class="logo">生产过程管理系统</div>
            </div>
            <div class="header-right">
                <span class="user-info">管理员</span>
                <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </header>
        
        <!-- 左侧菜单 -->
        <aside class="admin-sidebar">
            <ul class="menu-list">
                <li class="menu-item">
                    <a href="../homepage/administrator_home.html">
                        <span class="menu-icon">🏠</span>
                        <span class="menu-title">首页</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">👥</span>
                        <span class="menu-title">人员管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../person/person_list.html">人员列表</a></li>
                        <li><a href="../person/person_edit.html">添加人员</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📦</span>
                        <span class="menu-title">物料管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../material/material_list.html">物料列表</a></li>
                        <li><a href="../material/material_edit.html">添加物料</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">⚙️</span>
                        <span class="menu-title">设备管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../device/device_list.html">设备列表</a></li>
                        <li><a href="../device/device_edit.html">添加设备</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📝</span>
                        <span class="menu-title">产品管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="product_list.html">产品列表</a></li>
                        <li><a href="product_edit.html" class="active">添加产品</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">🏢</span>
                        <span class="menu-title">供应商管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../provider/provider_list.html">供应商列表</a></li>
                        <li><a href="../provider/provider_edit.html">添加供应商</a></li>
                    </ul>
                </li>
            </ul>
        </aside>
        
        <!-- 主内容区域 -->
        <main class="admin-main">
            <div class="content-wrapper">
                <div class="content-header">
                    <h2 id="pageTitle">添加产品</h2>
                </div>
                
                <div class="content-body">
                    <div class="form-container">
                        <form id="productForm">
                            <input type="hidden" id="productId">
                            <!-- 添加隐藏的产品编码字段 -->
                            <input type="hidden" id="productCode">
                            
                            <div class="form-group">
                                <label for="productName" class="form-label required-field">产品名称</label>
                                <input type="text" class="form-control" id="productName" required placeholder="请输入产品名称">
                            </div>
                            
                            <div class="form-group">
                                <label for="size" class="form-label required-field">外观尺寸</label>
                                <input type="text" class="form-control" id="size" required placeholder="请输入外观尺寸">
                            </div>
                            
                            <div class="form-group">
                                <label for="batch" class="form-label required-field">批次</label>
                                <input type="text" class="form-control" id="batch" required placeholder="请输入批次号">
                            </div>
                            
                            <div class="form-group">
                                <label for="operatorId" class="form-label">加工人员</label>
                                <select class="form-select" id="operatorId">
                                    <option value="">-- 选择加工人员 --</option>
                                    <!-- 人员选项将通过JavaScript动态加载 -->
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="processMethod" class="form-label required-field">加工方法</label>
                                <input type="text" class="form-control" id="processMethod" required placeholder="请输入加工方法">
                            </div>
                            
                            <div class="form-group">
                                <label for="processTime" class="form-label">加工时间</label>
                                <input type="datetime-local" class="form-control" id="processTime">
                            </div>
                            
                            <div class="form-group">
                                <label for="workshop" class="form-label required-field">加工车间</label>
                                <select class="form-select" id="workshop" required>
                                    <option value="">-- 选择车间 --</option>
                                    <option value="表面处理车间">表面处理车间</option>
                                    <option value="锻压车间">锻压车间</option>
                                    <option value="组装车间">组装车间</option>
                                    <option value="质检车间">质检车间</option>
                                </select>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-secondary btn-action" onclick="goBack()">返回</button>
                                <button type="submit" class="btn btn-primary btn-action">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script src="../../assets/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let isEditMode = false;
        let productId = null;
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function () {
            // 菜单展开/收起功能
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    // 只允许单开一个折叠区
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });

            // 添加首页链接的点击事件
            document.querySelector('.menu-item:first-child > a').addEventListener('click', function(e) {
                e.preventDefault(); // 阻止默认行为
                window.location.href = '../homepage/administrator_home.html'; // 跳转到管理员首页
            });

            // 默认展开产品管理菜单
            const productMenuItem = document.querySelector('.menu-item:nth-child(5)');
            if (productMenuItem) {
                productMenuItem.classList.add('active');
            }
            
            // 设置当前页面对应的菜单项为选中状态
            const currentPath = window.location.pathname;
            const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
            document.querySelectorAll('.submenu li a').forEach(link => {
                if (link.getAttribute('href') === filename) {
                    link.classList.add('active');
                }
            });
            
            // 获取URL参数
            const urlParams = new URLSearchParams(window.location.search);
            productId = urlParams.get('id');
            
            // 如果有ID参数，则是编辑模式
            if (productId) {
                isEditMode = true;
                document.getElementById('pageTitle').textContent = '编辑产品';
                // 加载产品数据
                loadProductData(productId);
            }
            
            // 加载人员数据
            loadOperators();
            
            // 表单提交事件
            document.getElementById('productForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveProduct();
            });
        });
        
        // 加载人员数据
        async function loadOperators() {
            try {
                const response = await fetch('http://localhost:8080/api/persons');
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                
                if (!Array.isArray(data)) {
                    throw new Error('返回数据格式错误');
                }
                
                const operatorSelect = document.getElementById('operatorId');
                // 清空现有选项
                operatorSelect.innerHTML = '<option value="">-- 选择加工人员 --</option>';
                
                // 添加新选项
                data.forEach(person => {
                    if (person && person.id && person.name) {
                        const option = document.createElement('option');
                        option.value = person.id;
                        option.textContent = `${person.name} (${person.jobNumber || ''})`;
                        operatorSelect.appendChild(option);
                    }
                });
            } catch (error) {
                console.error('加载人员数据失败:', error);
                // 显示更友好的错误信息
                const operatorSelect = document.getElementById('operatorId');
                operatorSelect.innerHTML = '<option value="">加载人员数据失败</option>';
                // 可以添加一个重试按钮或提示
                alert('加载人员数据失败: ' + (error.message || '请检查网络连接'));
            }
        }
        
        // 加载产品数据
        async function loadProductData(id) {
            try {
                const response = await fetch(`http://localhost:8080/api/products/${id}`);
                if (!response.ok) {
                    throw new Error('产品不存在');
                }
                
                const product = await response.json();
                
                // 填充表单
                document.getElementById('productId').value = product.id;
                document.getElementById('productCode').value = product.productCode;
                document.getElementById('productName').value = product.name;
                document.getElementById('size').value = product.size;
                document.getElementById('batch').value = product.batch;
                document.getElementById('processMethod').value = product.processMethod;
                document.getElementById('workshop').value = product.workshop;
                
                // 设置操作员
                if (product.operatorId) {
                    document.getElementById('operatorId').value = product.operatorId;
                }
                
                // 设置加工时间
                if (product.processTime) {
                    // 将后端返回的时间格式转换为input datetime-local支持的格式
                    const processTime = new Date(product.processTime);
                    const formattedTime = processTime.toISOString().slice(0, 16);
                    document.getElementById('processTime').value = formattedTime;
                }
                
            } catch (error) {
                console.error('加载产品数据失败:', error);
                alert('加载产品数据失败: ' + error.message);
                goBack();
            }
        }
        
        // 保存产品
        async function saveProduct() {
            // 获取表单数据
            const productData = {
                productCode: document.getElementById('productCode').value,
                name: document.getElementById('productName').value,
                size: document.getElementById('size').value,
                batch: document.getElementById('batch').value,
                processMethod: document.getElementById('processMethod').value,
                workshop: document.getElementById('workshop').value
            };
            
            // 可选字段
            const operatorSelect = document.getElementById('operatorId');
            const operatorId = operatorSelect.value;
            if (operatorId) {
                productData.operatorId = parseInt(operatorId);
                // 添加操作人员名称
                const selectedOption = operatorSelect.options[operatorSelect.selectedIndex];
                const operatorName = selectedOption ? selectedOption.textContent.split(' (')[0] : '';
                productData.operatorName = operatorName;
            }
            
            const processTime = document.getElementById('processTime').value;
            if (processTime) {
                productData.processTime = processTime;
            }
            
            try {
                let url = 'http://localhost:8080/api/products';
                let method = 'POST';
                
                // 如果是编辑模式
                if (isEditMode && productId) {
                    url = `${url}/${productId}`;
                    method = 'PUT';
                    productData.id = parseInt(productId);
                }
                
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(productData)
                });
                
                if (!response.ok) {
                    throw new Error('保存失败，服务器返回错误');
                }
                
                alert('产品保存成功！');
                
                // 保存成功后返回列表页
                goBack();
                
            } catch (error) {
                console.error('保存产品失败:', error);
                alert('保存产品失败: ' + error.message);
            }
        }
        
        // 返回列表页
        function goBack() {
            window.location.href = 'product_list.html';
        }
        
        function logout() {
    // 添加确认提示
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储的登录信息
        localStorage.removeItem('userInfo');
        localStorage.removeItem('token');
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    }
}
    </script>
</body>
</html>